-
Notifications
You must be signed in to change notification settings - Fork 745
/
MailKitMailProvider.cs
365 lines (307 loc) · 14.2 KB
/
MailKitMailProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Mail
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Mail.OAuth;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.DependencyInjection;
using MimeKit;
using Localize = DotNetNuke.Services.Localization.Localization;
/// <summary>A <see cref="MailProvider"/> implementation using <see cref="SmtpClient"/>).</summary>
public class MailKitMailProvider : MailProvider
{
private static readonly Regex SmtpServerRegex = new Regex("^[^:]+(:[0-9]{1,5})?$", RegexOptions.Compiled);
private readonly Lazy<ISmtpOAuthController> smtpOAuthController;
/// <summary>Initializes a new instance of the <see cref="MailKitMailProvider"/> class.</summary>
[Obsolete("Deprecated in DotNetNuke 9.13.0. Use overload taking Lazy<ISmtpOAuthProvider>. Scheduled removal in v11.0.0.")]
public MailKitMailProvider()
: this(null)
{
}
/// <summary>Initializes a new instance of the <see cref="MailKitMailProvider"/> class.</summary>
/// <param name="smtpOAuthController">The SMTP OAuth controller.</param>
public MailKitMailProvider(Lazy<ISmtpOAuthController> smtpOAuthController)
{
this.smtpOAuthController = smtpOAuthController ?? Globals.DependencyProvider.GetRequiredService<Lazy<ISmtpOAuthController>>();
}
/// <inheritdoc />
public override bool SupportsOAuth => true;
/// <inheritdoc />
public override string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null)
{
try
{
var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo);
if (errorMessage != null)
{
return errorMessage;
}
var mailMessage = CreateMailMessage(mailInfo, smtpInfo);
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect(host, port, SecureSocketOptions.Auto);
if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password))
{
smtpClient.Authenticate(smtpInfo.Username, smtpInfo.Password);
}
var (provider, portalId) = this.GetOAuthProvider(smtpClient, smtpInfo);
if (provider != null)
{
provider.Authorize(portalId, new OAuthSmtpClient(smtpClient));
}
smtpClient.Send(mailMessage);
smtpClient.Disconnect(true);
}
return string.Empty;
}
catch (Exception exc)
{
return HandleException(exc);
}
}
/// <inheritdoc />
public override async Task<string> SendMailAsync(MailInfo mailInfo, SmtpInfo smtpInfo = null, CancellationToken cancellationToken = default(CancellationToken))
{
var (host, port, errorMessage) = ParseSmtpServer(ref smtpInfo);
if (errorMessage != null)
{
return errorMessage;
}
var mailMessage = CreateMailMessage(mailInfo, smtpInfo);
try
{
using (var smtpClient = new SmtpClient())
{
await smtpClient.ConnectAsync(host, port, SecureSocketOptions.Auto, cancellationToken);
if (smtpInfo.Authentication == "1" && !string.IsNullOrEmpty(smtpInfo.Username) && !string.IsNullOrEmpty(smtpInfo.Password))
{
await smtpClient.AuthenticateAsync(smtpInfo.Username, smtpInfo.Password, cancellationToken);
}
var (provider, portalId) = this.GetOAuthProvider(smtpClient, smtpInfo);
if (provider != null)
{
await provider.AuthorizeAsync(portalId, new OAuthSmtpClient(smtpClient), cancellationToken);
}
await smtpClient.SendAsync(mailMessage, cancellationToken);
await smtpClient.DisconnectAsync(true, cancellationToken);
}
return string.Empty;
}
catch (Exception exc)
{
return HandleException(exc);
}
}
private static (string host, int port, string errorMessage) ParseSmtpServer(ref SmtpInfo smtpInfo)
{
var port = 25;
if (smtpInfo == null || string.IsNullOrEmpty(smtpInfo.Server))
{
if (string.IsNullOrWhiteSpace(Host.SMTPServer))
{
return (null, port, "SMTP Server not configured");
}
smtpInfo = new SmtpInfo
{
Server = Host.SMTPServer,
Authentication = Host.SMTPAuthentication,
Username = Host.SMTPUsername,
Password = Host.SMTPPassword,
EnableSSL = Host.EnableSMTPSSL,
AuthProvider = Host.SMTPAuthProvider,
};
}
if (smtpInfo.Authentication == "2")
{
throw new NotSupportedException("NTLM authentication is not supported by MailKit provider");
}
smtpInfo.Server = smtpInfo.Server.Trim();
if (!SmtpServerRegex.IsMatch(smtpInfo.Server))
{
return (null, port, Localize.GetString("SMTPConfigurationProblem"));
}
var smtpHostParts = smtpInfo.Server.Split(':');
var host = smtpHostParts[0];
if (smtpHostParts.Length <= 1)
{
return (host, port, null);
}
// port is guaranteed to be of max 5 digits numeric by the RegEx check
port = int.Parse(smtpHostParts[1]);
if (port < 1 || port > 65535)
{
return (host, port, Localize.GetString("SmtpInvalidPort"));
}
return (host, port, null);
}
private static string HandleException(Exception exc)
{
var retValue = Localize.GetString("SMTPConfigurationProblem") + " ";
// mail configuration problem
if (exc.InnerException != null)
{
retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
Exceptions.Exceptions.LogException(exc.InnerException);
}
else
{
retValue += exc.Message;
Exceptions.Exceptions.LogException(exc);
}
return retValue;
}
private static MimeMessage CreateMailMessage(MailInfo mailInfo, SmtpInfo smtpInfo)
{
var mailMessage = new MimeMessage();
mailMessage.From.Add(ParseAddressWithDisplayName(displayName: mailInfo.FromName, address: mailInfo.From));
if (!string.IsNullOrEmpty(mailInfo.Sender))
{
mailMessage.Sender = MailboxAddress.Parse(mailInfo.Sender);
}
// translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
if (!string.IsNullOrEmpty(mailInfo.To))
{
mailInfo.To = mailInfo.To.Replace(";", ",");
mailMessage.To.AddRange(InternetAddressList.Parse(mailInfo.To));
}
if (!string.IsNullOrEmpty(mailInfo.CC))
{
mailInfo.CC = mailInfo.CC.Replace(";", ",");
mailMessage.Cc.AddRange(InternetAddressList.Parse(mailInfo.CC));
}
if (!string.IsNullOrEmpty(mailInfo.BCC))
{
mailInfo.BCC = mailInfo.BCC.Replace(";", ",");
mailMessage.Bcc.AddRange(InternetAddressList.Parse(mailInfo.BCC));
}
if (!string.IsNullOrEmpty(mailInfo.ReplyTo))
{
mailInfo.ReplyTo = mailInfo.ReplyTo.Replace(";", ",");
mailMessage.ReplyTo.AddRange(InternetAddressList.Parse(mailInfo.ReplyTo));
}
mailMessage.Priority = ToMessagePriority(mailInfo.Priority);
// Only modify senderAddress if smtpAuthentication is enabled
// Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
if (smtpInfo.Authentication == "1" || smtpInfo.Authentication == "2")
{
// if the senderAddress is the email address of the Host then switch it smtpUsername if different
// if display name of senderAddress is empty, then use Host.HostTitle for it
if (mailMessage.Sender != null)
{
var senderAddress = mailInfo.Sender;
var senderDisplayName = mailInfo.FromName;
var needUpdateSender = false;
if (smtpInfo.Username.Contains("@")
&& senderAddress == Host.HostEmail
&& !senderAddress.Equals(smtpInfo.Username, StringComparison.InvariantCultureIgnoreCase))
{
senderAddress = smtpInfo.Username;
needUpdateSender = true;
}
if (string.IsNullOrEmpty(senderDisplayName))
{
senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
needUpdateSender = true;
}
if (needUpdateSender)
{
mailMessage.Sender = ParseAddressWithDisplayName(
displayName: senderDisplayName,
address: senderAddress);
}
}
else if (smtpInfo.Username.Contains("@"))
{
mailMessage.Sender = ParseAddressWithDisplayName(
displayName: Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle,
address: smtpInfo.Username);
}
}
var builder = new BodyBuilder { TextBody = Mail.ConvertToText(mailInfo.Body), };
if (mailInfo.BodyFormat == MailFormat.Html)
{
builder.HtmlBody = mailInfo.Body;
}
// attachments
if (mailInfo.Attachments != null)
{
foreach (var attachment in mailInfo.Attachments.Where(attachment => attachment.Content != null))
{
builder.Attachments.Add(attachment.Filename, attachment.Content, ContentType.Parse(attachment.ContentType));
}
}
// message
mailMessage.Subject = HtmlUtils.StripWhiteSpace(mailInfo.Subject, true);
mailMessage.Body = builder.ToMessageBody();
return mailMessage;
}
private static MailboxAddress ParseAddressWithDisplayName(string displayName, string address)
{
var mailboxAddress = MailboxAddress.Parse(address);
if (!string.IsNullOrWhiteSpace(displayName))
{
mailboxAddress.Name = displayName;
}
return mailboxAddress;
}
private static MessagePriority ToMessagePriority(MailPriority priority)
{
switch (priority)
{
case MailPriority.Low:
return MessagePriority.NonUrgent;
case MailPriority.Normal:
return MessagePriority.Normal;
case MailPriority.High:
return MessagePriority.Urgent;
default:
throw new ArgumentException($"Invalid MailPriority value: {priority}", nameof(priority));
}
}
private (ISmtpOAuthProvider, int) GetOAuthProvider(SmtpClient smtpClient, SmtpInfo smtpInfo)
{
var usingOAuth = smtpInfo.Authentication == "3";
if (usingOAuth)
{
var authProvider = this.smtpOAuthController.Value.GetOAuthProvider(smtpInfo.AuthProvider);
if (authProvider != null)
{
var portalId = Null.NullInteger;
if (Host.SMTPPortalEnabled)
{
portalId = PortalSettings.Current.PortalId;
}
return (authProvider, portalId);
}
}
return (null, Null.NullInteger);
}
private class OAuthSmtpClient : IOAuth2SmtpClient
{
public OAuthSmtpClient(ISmtpClient smtpClient)
{
this.SmtpClient = smtpClient;
}
public ISmtpClient SmtpClient { get; }
public void Authenticate(string username, string token)
{
this.SmtpClient.Authenticate(new SaslMechanismOAuth2(username, token));
}
public Task AuthenticateAsync(string username, string token, CancellationToken cancellationToken = default(CancellationToken))
{
return this.SmtpClient.AuthenticateAsync(new SaslMechanismOAuth2(username, token), cancellationToken);
}
}
}
}